package com.kylin.core.user.web.facade.impl;

import com.kylin.core.user.query.handler.UserInfoTranslator;
import com.kylin.domain.oauth2.social.wechat.EncryptedUserData;
import com.kylin.domain.oauth2.social.wechat.connect.WechatServiceProvider;
import com.kylin.domain.user.vo.WechatUserInfoVO;
import com.kylin.shared.common.ResponseWrapper;
import com.kylin.shared.common.anno.ArgsValid;
import com.kylin.shared.enums.ResultCodeEnum;
import com.kylin.user.api.dto.req.UpdateUserInfoReqDTO;
import com.kylin.user.api.dto.req.UpdateUserPhoneReqDTO;
import com.kylin.user.api.dto.resp.UserInfoRespDTO;
import com.kylin.user.api.web.facade.AuthenticationFacade;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.RestController;

/**
 * 认证相关接口实现
 * @author Damon S.
 * @version v1.0.1
 * @date 2020年11月14日 14:46
 */
@RestController
@RequiredArgsConstructor
@Api(tags = "用户认证接口")
public class AuthenticationFacadeImpl implements AuthenticationFacade {

    private final WechatServiceProvider provider;
    private final UserInfoTranslator translator;

    @Override
    @ApiOperation(value = "微信小程序登录", notes = "微信小程序登录")
    public ResponseWrapper<UserInfoRespDTO> wxLogin(String code) {
        return new ResponseWrapper<>(
                translator.toUserInfoRespDTO(provider.wxLogin(code))
        );
    }

    @ArgsValid
    @Override
    @ApiOperation(value = "更新用户信息", notes = "更新用户信息")
    public ResponseWrapper<Boolean> updateUserDetail(UpdateUserInfoReqDTO req) {
        return new ResponseWrapper<>(provider.updateUserInfo(
                EncryptedUserData.builder()
                        .userId(req.getUserId())
                        .encryptedData(req.getEncryptedData())
                        .signature(req.getSignature())
                        .iv(req.getIv()).build()
        ));
    }

    @ArgsValid
    @Override
    @ApiOperation(value = "更新手机信息", notes = "更新手机信息")
    public ResponseWrapper<String> updatePhoneNo(UpdateUserPhoneReqDTO req) {
        WechatUserInfoVO userInfoVO = provider.updatePhoneNo(
                EncryptedUserData.builder()
                        .userId(req.getUserId())
                        .encryptedData(req.getEncryptedData())
                        .iv(req.getIv()).build()
        );
        if (WechatUserInfoVO.EMPTY == userInfoVO) {
            return new ResponseWrapper<>(ResultCodeEnum.INTERNAL_ERROR);
        }
        return new ResponseWrapper<>(userInfoVO.getPhoneNumber());
    }
}
